package test;

import java.util.concurrent.atomic.AtomicStampedReference;

public class AtomicStampedReferenceExample {
    private static AtomicStampedReference<Integer> value = new AtomicStampedReference<>(1, 0);

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(() -> {
            int stamp = value.getStamp();
            System.out.println("t1 read value=" + value.getReference() + ", stamp=" + stamp);

            // 模拟 ABA 问题
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            int stamp1 = value.getStamp();
            System.out.println("版本号已被修改为："+stamp1+"，然而获取的版本号仍为"+stamp);
            boolean success = value.compareAndSet(1, 2, stamp, stamp + 1);
            System.out.println("t1 CAS result=" + success+", stamp=" + stamp);
        });

        Thread t2 = new Thread(() -> {
            int stamp = value.getStamp();
            System.out.println("t2 read value=" + value.getReference() + ", stamp=" + stamp);

            boolean success = value.compareAndSet(1, 3, stamp, stamp + 1);
            int i = stamp + 1;
            System.out.println("t2 CAS result=" + success+", 新的stamp=" + i);
        });

        t1.start();
        t2.start();

        t1.join();
        t2.join();
    }
}

